// pages/messageSystem/messageList/messageList.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        messageType: null,
        messageList: [],
        nowPage: 0,
        isLoading: false,
        isAll: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            messageType: options.messageType
        })
        this.getMessageList()
        this.checkMessage()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData({
            messageList: [],
            nowPage: 0,
            isLoading: false,
            isAll: false
        })
        common.refresh()
        setTimeout(function () {
            wx.stopPullDownRefresh()
        }, 2000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getMessageList()
    },

    getMessageList: function () {
        if (this.data.isLoading) {
            return
        }
        if (this.data.isAll) {
            return
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '加载中',
        })
        const that = this
        let messageList = this.data.messageList
        let data = {
            type: this.data.messageType,
            limit: 10,
            page: this.data.nowPage,
            order_by: 'add_time'
        }
        common.post('System/send_list', data).then(function (res) {
            that.setData({
                isLoading: false
            })
            wx.hideLoading()
            if (res.code == 204) {
                that.setData({
                    messageList: messageList,
                    isAll: true
                })
            } else {
                messageList = messageList.concat(res)
                that.setData({
                    messageList: messageList,
                    nowPage: that.data.nowPage + 1
                })
            }
        }).catch(function (e) { })
    },

    checkMessage: function () {
        let data = {
            type: this.data.messageType
        }
        common.post('System/read', data).then(function (res) { }).catch(function (e) { })
    }
})